#!/usr/bin/python3
# -*- coding: utf-8 -*-

from diskcache import Cache

from public.project_patch import CACHE_DIR


class CacheManager:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls, *args)
        return cls.__instance

    def __init__(self, cache_dir=CACHE_DIR):
        self.cache = Cache(cache_dir, size_limit=100 * 1024 * 1024)

    def get(self, key):
        """Retrieve a value from the cache."""
        return self.cache.get(key)

    def set(self, key, value, expire=None):
        """Set a value in the cache."""
        self.cache.set(key, value, expire=expire)

    def delete(self, key):
        """Delete a key from the cache."""
        self.cache.delete(key)

    def clear(self):
        """Clear all items from the cache."""
        self.cache.clear()

    def expire(self):
        """Expire all items in the cache."""
        self.cache.expire()

    def __contains__(self, key):
        """Check if a key exists in the cache."""
        return key in self.cache

    def __getitem__(self, key):
        """Retrieve an item by its key."""
        return self.get(key)

    def __setitem__(self, key, value):
        """Set an item by its key."""
        self.set(key, value)

    def __delitem__(self, key):
        """Delete an item by its key."""
        self.delete(key)

    def __len__(self):
        """Return the number of items in the cache."""
        return len(self.cache)

    def iterkeys(self):
        """Iterate over keys in the cache."""
        return iter(self.cache)

    def get_all(self):
        """get all items in the cache."""
        datas = {}
        all_cache = self.iterkeys()
        for cache_key in all_cache:
            datas[cache_key] = self.get(cache_key)
        return datas


cache_manager = CacheManager()


if __name__ == "__main__":
    cache_manager['key1'] = 'value1'
    print(cache_manager['key1'])  # 输出: value1
    del cache_manager['key1']
    print('key1' in cache_manager)  # 输出: False
    res = cache_manager.get_all()
    print(res)
